//
//  HNAction.m
//  HeroNuts
//
//  Created by Magic on 4/2/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "HNAction.h"
#import "HNActionCache.h"

@interface HNAction()

-(void) runRestSequence;

@end

@implementation HNAction

#pragma mark HNAction - initialization - preparing the action sequence to be run

- (id)initWithActorName:(NSString *)actor action:(NSString *)action
{
    if ((self = [super init])) 
	{
        actions_ = [[NSMutableArray alloc] init];
        
        CCAnimate *animate = [[HNActionCache sharedActionCache] actionByName:action actor:actor];
        CCCallFunc *playEffect = [CCCallFunc actionWithTarget:self selector:@selector(playSoundEffect)];
        
        CCSpawn *animateWithSound = [CCSpawn actionOne:animate two:playEffect];
        [actions_ addObject:animateWithSound];
    }
    
    return self;
}

- (void)playSoundEffect
{
    //to be overwritten by sub actions
}


#pragma mark HNAction - running the action sequence

-(void) startWithTarget:(HNActor*)aTarget
{
    target_ = aTarget;
    
    //to run the actions in actions_ one after another   
    [self runRestSequence];
}

-(void) runRestSequence
{
    if ([actions_ count]>currentElement_) {
        CCCallFunc *runNext = [CCCallFunc actionWithTarget:self selector:_cmd];
        CCSequence *nextAction = [CCSequence actions:[actions_ objectAtIndex:currentElement_],runNext,nil];
        [target_.sprite runAction:nextAction]; 
        currentElement_++;
    }
    else
    {
        [self restore];
    }
}

#pragma mark HNAction - restore original frame 

- (void)restore
{
    CCAnimate *restore = [[HNActionCache sharedActionCache] actionByName:@"RESTORE" actor:target_.name];
    CCCallFunc *notify = [CCCallFunc actionWithTarget:self selector:@selector(onRestoreFinished)];
    CCSequence *sequence = [CCSequence actions:restore,notify, nil];
    
    [target_.sprite runAction:sequence];
}

- (void)onRestoreFinished
{      
    [self notifyCompletion];
}

- (void)notifyCompletion
{      
    //notify the flow control center
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ACTIONFINISHED" object:self];
}

#pragma mark HNAction - dealloc

- (void) dealloc
{
    [actions_ release];
	[super dealloc];
}

@end
